package com.chen.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.reggie.common.CustomException;
import com.chen.reggie.common.R;
import com.chen.reggie.dto.SetmealDto;
import com.chen.reggie.mapper.SetmealMapper;
import com.chen.reggie.pojo.Setmeal;
import com.chen.reggie.pojo.SetmealDish;
import com.chen.reggie.service.SetmealDishService;
import com.chen.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @ClassName SetmealServiceImpl
 * @Description TODO
 * @Author hainc
 * @Date 2022/9/4 21:12
 * @Version 1.0
 **/
@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    //新增套餐，保存套餐和菜品的关系数据
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐基本信息，套餐表
        this.save(setmealDto);

        //保存套餐和菜品的关联信息，setmeal_dish表
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for(SetmealDish setmealDish:setmealDishes){
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);

    }

    //删除套餐，删除套餐和菜品的关联数据
    @Transactional
    public void removeWithDish(@RequestParam List<Long> ids) {
        //查询套餐状态，确定是否可用删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids!=null,Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);

        int count = this.count(queryWrapper);

        if(count > 0){
            //如果不能删除，抛出业务异常
            throw new CustomException("套餐正在售卖中，不能删除");
        }

        //如果可以删除，先删除套餐中的数据
        this.removeByIds(ids);

        //删除关系表数据，套餐对应的菜品信息,这里不可以用removeByids,因为传递过来的是套餐id不是套餐菜品id
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        //根据setmealId删除
        setmealDishService.remove(setmealDishLambdaQueryWrapper);


    }



}
